package com.twu.biblioteca.utils;

import java.io.*;

/**
 * Created by Enrico on 17/09/2014.
 */
public class IdDriver {

    private static final String FILENAME = "uniqueId.data";

    public static int getUniqueId() {
        int lastId = 0;

        // Get Last ID
        try {
            lastId = getLastId();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Make new ID
        int uniqueId = lastId + 1;

        // Save latest ID
        try {
            saveUniqueId(uniqueId);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return uniqueId; // return unique ID
    }

    private static int getLastId() throws IOException {

        // Create and check if file exists
        File inFile = new File(getFilePath());
        if (!inFile.exists()) {
            // Create new file and save int 0 to it.
            inFile.createNewFile();
            saveUniqueId(0);
        }

        FileInputStream inFileStream = new FileInputStream(inFile);
        DataInputStream inDataStream = new DataInputStream(inFileStream);
        int lastID = inDataStream.readInt();
        inDataStream.close();

        return lastID; // return last id that was saved to file.
    }

    private static void saveUniqueId(int uniqueId) throws IOException {
        File outFile = new File(getFilePath());
        FileOutputStream outFileStream = new FileOutputStream(outFile);
        DataOutputStream outDataStream = new DataOutputStream(outFileStream);
        outDataStream.writeInt(uniqueId);
        outDataStream.close();
    }

    private static String getFilePath(){
        String workingDir = System.getProperty("user.dir");
        return workingDir + "/resources/" + FILENAME;
    }
}
